<template>
  <el-dialog
    ref="MusicPro"
    title="选择代理"
    width="400px"
    :close-on-click-modal="false"
    :visible.sync="params.visible"
  >
    <compTree
      ref="tree"
      :show-search="false"
      :comp-tree-height="350"
      :tree-show-checkbox="data.ismutil"
      :tree-default-expanded-keys="treeDefaultExpandedKeys"
      :show-right-tag="true"
      :tree-data="treeData"
    />
    <dialog-btn slot="footer">
      <el-button
        v-if="data.ismutil"
        type="primary"
        style="float: left"
        @click="onSelectPlan"
      >选择方案</el-button>
    </dialog-btn>

    <select-agent-plan
      v-if="selectAgentPlanParams.visible"
      :params="selectAgentPlanParams"
    />
  </el-dialog>
</template>

<script>
/**
 * *********************************************原selectagent.html页面***************************************************
 * 入参：params: {
 *          ismutil(可选) Boolean
 *          filterOnline(可选) Boolean
 *          agentId
 *      }
 * 出参：{
 *    agentId.
 *    agentIP,
 *    agentName,
 *    agentSystem
 * }
 */

import { ParamArr, SQLTable } from '../../../public/js/paramarr'
import Global from '../../../public/js/global'
import { getAgentList } from '@/api/event'
import SelectAgentPlan from '@/views/publish/dialog/SelectAgentPlan.vue'
export default {
  name: 'SelectAgent',
  components: { SelectAgentPlan },
  props: {
    params: {
      type: Object,
      default() {
        return {
          visible: false,
          ismutil: '',
          filterOnline: '',
          agentId: ''
        }
      }
    }
  },
  data() {
    return {
      data: {}, // 接收入参
      treeData: [],
      treeDefaultExpandedKeys: [],
      selectAgentPlanParams: {
        visible: false,
        agentId: ''
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // this.$showLoading(
      //   '正在加载中',
      //   this.$refs.MusicPro.$el.querySelector('div')
      // )
      this.data = this.params
      if (this.data.ismutil === undefined) this.data.ismutil = false
      if (this.data.filterOnline === undefined) this.data.filterOnline = false
      const vPar = new ParamArr()
      vPar.setStr('r_agentId', this.data.agentId)
      getAgentList(vPar).then((vPar) => {
        const agentId = vPar.getStr('r_agentId')
        const ismulti = this.data.ismutil
        const nodes = []
        const nodeMap = new Map()
        // 分组
        let table = new SQLTable(vPar.getTable('k_agent_group'))
        table.first()
        while (!table.eof()) {
          const pnode = Global.getTreeviewPNode(
            nodeMap,
            nodes,
            table.getValueByName('PID')
          )
          const node = {}
          node['id'] = table.getValueByName('ID')
          node['text'] = table.getValueByName('Name')
          node['icon'] = 'wenjianyi'
          node['type'] = 1
          pnode.push(node)
          nodeMap.set(table.getValueByName('ID'), node)
          table.next()
        }
        // 机器
        table = new SQLTable(vPar.getTable('k_agent'))
        table.first()
        while (!table.eof()) {
          const pnode = Global.getTreeviewPNode(
            nodeMap,
            nodes,
            table.getValueByName('PID')
          )
          const node = {}
          node['id'] = table.getValueByName('ID')
          node['ip'] = table.getValueByName('IP')
          node['name'] = table.getValueByName('Name')
          node['text'] = Global.strFormat(
            '{0} [{1}]',
            node['ip'],
            node['name']
          )
          node['type'] = 2
          node['online'] = table.getIntByName('Online')
          // 机器是否在线
          if (node['online'] === 0) {
            node['tag'] = { effect: 'dark', type: 'info', text: '离线' }
          } else {
            node['tag'] = { effect: 'dark', type: 'success', text: '在线' }
          }
          node['system'] = table.getValueByName('System')
          node['icon'] = Global.getSystemIconStr(node['system'])
          if (!ismulti && node.id === agentId) {
            // node['state'] = { selected: true }
            this.$refs.tree.setSelect(agentId)
          }
          if (!(this.data.filterOnline && node['online'] === 0)) {
            pnode.push(node)
          }
          nodeMap.set(node.id, node)
          table.next()
        }
        this.treeData = nodes
        if (this.data.filterOnline) {
          const newNodes = []
          for (let i = 0; i < this.treeData.length; i++) {
            this.treeData[i]['remove'] = false
            this.removeParentNode(this.treeData[i])
            if (!this.treeData[i]['remove']) newNodes.push(this.treeData[i])
          }
          this.treeData = newNodes
        }
        // 选中回显
        if (!ismulti && this.params.agentId) {
          this.$refs.tree.setCurrentKey(this.params.agentId)
          this.treeDefaultExpandedKeys.push(this.params.agentId)
        }
        // 勾选回显
        if (ismulti && this.params.agentId) {
          const agents = this.params.agentId.split(',')
          this.$refs.tree.setCheckedKeys(agents)
          for (let i = 0; i < agents.length; i++) {
            this.treeDefaultExpandedKeys.push(agents[i])
          }
        }
      })
    },
    removeParentNode(node) {
      if (node['type'] === 1) {
        if (node['nodes'] === undefined || node['nodes'] === '') {
          node['remove'] = true
        } else {
          node['remove'] = false
          const subnode = node['nodes']
          const newNodes = []
          for (let i = 0; i < subnode.length; i++) {
            this.removeParentNode(subnode[i])
            if (!subnode[i]['remove']) newNodes.push(subnode[i])
          }
          node['nodes'] = newNodes
          if (node['nodes'] === undefined || node['nodes'] === '') {
            node['remove'] = true
          }
        }
      }
    },
    onSelectPlan() {
      this.selectAgentPlanParams = {
        visible: true,
        agentId: ''
      }
      this.selectAgentPlanParams.confirm = (params) => {
        for (let i = 0; i < this.treeData.length; i++) {
          if (params.nodes.indexOf(this.treeData[i].name) !== -1) {
            this.$refs.tree.setChecked(this.treeData[i], true)
          }
        }
        this.selectAgentPlanParams.visible = false
      }
    },
    confirm() {
      const params = {}
      if (this.data.ismutil) {
        const nodesChecked = this.$refs.tree.getCheckedNodes()
        if (nodesChecked.length === 0) { return this.$message.warning('请选择代理端') }
        const arrID = []
        const arrIP = []
        const arrName = []
        const arrSystem = []
        for (let i = 0; i < nodesChecked.length; i++) {
          const node = nodesChecked[i]
          if (node['type'] === 2) {
            arrID.push(node['id'])
            arrIP.push(node['ip'])
            arrName.push(node['name'])
            arrSystem.push(node['system'])
          }
        }
        if (this.data.filterOnline && arrID.length === 0) {
          return this.$message.warning('请选择代理端')
        }
        params.agentId = arrID.toString()
        params.agentIP = arrIP.toString()
        params.agentName = arrName.toString()
        params.agentSystem = arrSystem.toString()
      } else {
        const node = this.$refs.tree.getCurrentNode()
        if (node === null) return this.$message.warning('请选择代理端')
        params.agentId = node['id']
        params.agentIP = node['ip']
        params.agentName = node['name']
        params.agentSystem = node['system']
      }
      if (this.params.confirm !== undefined) {
        this.params.confirm(params)
      } else {
        this.$emit('confirm', params)
      }
    }
  }
}
</script>

<style scoped>
</style>
